package com.suning.sawp.in.controller.task;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import com.suning.sawp.constants.ErrorCodeConstants;
import com.suning.sawp.constants.LoggerConstants;
import com.suning.sawp.constants.MainPushConstants;
import com.suning.sawp.constants.MainPushErrorConstants;
import com.suning.sawp.dto.common.QueryResult;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.dto.precharge.CommonRtn;
import com.suning.sawp.in.controller.DjBaseController;
import com.suning.sawp.in.controller.MyGsonView;
import com.suning.sawp.intf.mainpushnew.MainPushTaskHqHandleService;
import com.suning.sawp.po.mainpushnew.HqTask;
import com.suning.sawp.service.util.ExcelUtils;
import com.suning.sawp.service.util.RedisCacheUtils;
import com.suning.sawp.vo.mainpushnew.HqModelAllocateFormVo;

/**
 * 
 * 总部主推任务维护控制层<br>
 *
 * @author 14060886 祝翔龙
 */
@RequestMapping("/adminPage/task/hq/handle")
@Controller
public class MainPushTaskHqHandleController extends DjBaseController {

	private static final Logger LOGGER = LoggerFactory.getLogger(LoggerConstants.SAWP_SERVICE);

	@Autowired
	private MainPushTaskHqHandleService mainPushTaskHqHandleService;

	@Resource
	private RedisCacheUtils cacheUtils;

	/**
	 * 查询总部主推任务
	 *
	 * @param taskTopic
	 * @param month
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("/showTaskList.do")
	public MyGsonView showTaskList(String taskTopic, String month, Integer pageNo, Integer pageSize) {
		LOGGER.debug("showTaskList input taskTopic:" + taskTopic + ",month:" + month);
		Map<String, Integer> pageMap = super.getPageParams(pageNo, pageSize);
		Map<String, Object> queryMaps = new HashMap<String, Object>();
		queryMaps.putAll(pageMap);
		queryMaps.put("taskTopic", taskTopic);
		queryMaps.put("month", month);
		queryMaps.put("taskStatus", 1);

		ReturnMsg<QueryResult<HqTask>> ret = mainPushTaskHqHandleService.queryPageHqTask(queryMaps);
		return setGsonView(ret);
	}

	/**
	 * 查询创建中的任务列表
	 *
	 * 导入第一个excel之后，会跳转到临时页面，获取所选月份创建中的任务数据
	 *
	 * @return
	 */
	@RequestMapping("/showTmpTaskList.do")
	public MyGsonView showTmpTaskList(String month) {
		Map<String, Integer> pageMap = super.getPageParams(1, 20);
		Map<String, Object> queryMaps = new HashMap<String, Object>();
		queryMaps.putAll(pageMap);
		queryMaps.put("month", month);
		queryMaps.put("taskStatus", 0);

		ReturnMsg<QueryResult<HqTask>> ret = mainPushTaskHqHandleService.queryPageHqTask(queryMaps);
		return setGsonView(ret);
	}

	/**
	 * 
	 * 功能描述: 查询主推任务信息<br>
	 *
	 * @param hqTaskId
	 * @return
	 */
	@RequestMapping("/queryTaskInfo.do")
	public MyGsonView queryTaskInfo(Long hqTaskId) {
		LOGGER.debug("queryTaskInfo input hqTaskId: " + hqTaskId);
		return setGsonView(mainPushTaskHqHandleService.queryTaskInfo(hqTaskId));
	}

	/**
	 * 
	 * 功能描述: 查询主推任务款数信息<br>
	 *
	 * @param hqTaskId
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("/queryTaskModelDetail.do")
	public MyGsonView queryTaskModelDetail(Long hqTaskId, Integer pageNo, Integer pageSize) {
		LOGGER.debug("queryTaskModelDetail input hqTaskId: " + hqTaskId + ";pageNo: " + pageNo + ";pageSize: " + pageSize);
		return setGsonView(mainPushTaskHqHandleService.queryTaskModelDetail(hqTaskId, super.getPageParams(pageNo, pageSize)));
	}

	/**
	 * 
	 * 功能描述: 查询主推任务款数分配信息<br>
	 *
	 * @param hqTaskId
	 * @param modelId
	 * @return
	 */
	@RequestMapping("/queryAreaAllocateDetail.do")
	public MyGsonView queryAreaAllocateDetail(Long hqTaskId, Long modelId) {
		LOGGER.debug("queryTaskModelDetail input hqTaskId: " + hqTaskId + ";modelId: " + modelId);
		return setGsonView(mainPushTaskHqHandleService.queryAreaAllocateDetail(hqTaskId, modelId));
	}

	/**
	 * 
	 * 功能描述: 总部分配款数的目标台数<br>
	 *
	 * @param areaAllocates
	 * @return
	 */
	@RequestMapping("/allocateModel.do")
	@ResponseBody
	public ReturnMsg<CommonRtn> allocateModel(HqModelAllocateFormVo areaAllocates) {
		LOGGER.debug("allocateModel input areaAllocates: " + areaAllocates);
		return mainPushTaskHqHandleService.allocateModel(areaAllocates);
	}

	/**
	 * 
	 * 功能描述: 修改目标占比<br>
	 *
	 * @param hqTaskId
	 * @param rate
	 * @return
	 */
	@RequestMapping("/modifyTaskRate.do")
	public MyGsonView modifyTaskRate(Long hqTaskId, String rate) {
		LOGGER.debug("modifyTaskRate input hqTaskId: " + hqTaskId + ";rate: " + rate);
		return setGsonView(mainPushTaskHqHandleService.modityTaskRate(hqTaskId, rate));
	}

	/**
	 * 
	 * 功能描述: 删除款数<br>
	 *
	 * @param hqTaskId
	 * @param modelId
	 * @return
	 */
	@RequestMapping("/removeModel.do")
	public MyGsonView removeModel(Long hqTaskId, Long modelId) {
		LOGGER.debug("removeModel input hqTaskId: " + hqTaskId + ";modelId: " + modelId);
		return setGsonView(mainPushTaskHqHandleService.removeModel(hqTaskId, modelId));
	}

	/**
	 * 
	 * 功能描述: 新增款数<br>
	 *
	 * @param file
	 * @param hqTaskId
	 * @return
	 */
	@RequestMapping("/addModel.do")
	public MyGsonView addModel(@RequestParam(value = "file", required = true) MultipartFile file, Long hqTaskId) {
		LOGGER.debug("removeModel input hqTaskId: " + hqTaskId);
		ReturnMsg<CommonRtn> result = new ReturnMsg<CommonRtn>();
		try {
			Workbook wookbook = ExcelUtils.createWb(file);
			Sheet sheet = wookbook.getSheetAt(0);
			result = mainPushTaskHqHandleService.addModel(sheet, hqTaskId);
		} catch (Exception e) {
			LOGGER.error("新增款数失败", e);
			result.setError(ErrorCodeConstants.MAIN_PUSH_ERR_E007, e.getMessage());
		}
		return setGsonView(result);
	}

	/**
	 * 
	 * 主推总部任务导入第一个excel（占比数据,款数商品关系数据）
	 *
	 * @param hqTaskId
	 * @return
	 */
	@RequestMapping("/importFirstExcel.do")
	@ResponseBody
	public ReturnMsg<List<String>> importFirstExcel(HttpServletRequest request) {
		LOGGER.debug("创建总部主推任务：导入first excel!");
		MultipartRequest mutilRequest = (MultipartRequest) request;
		MultipartFile file = mutilRequest.getFile("firstExcel");
		String month = request.getParameter("month");

		ReturnMsg<List<String>> returnMsg = new ReturnMsg<List<String>>();
		// 参数错误
		if (file == null || month == null || month.length() != 6) {
			returnMsg.setError(MainPushErrorConstants.TASK_ERR_PARAMS, MainPushErrorConstants.MAIN_PUSH_ERR_MAP);
			return returnMsg;
		}

		return mainPushTaskHqHandleService.importFirstExcel(file, month);
	}

	/**
	 * 
	 * 主推总部任务导入第二个excel（品类，大区，款数,目标数量关系数据）
	 *
	 * @param hqTaskId
	 * @return
	 */
	@RequestMapping("/importSecondExcel.do")
	@ResponseBody
	public ReturnMsg<List<String>> importSecondExcel(HttpServletRequest request) {
		LOGGER.debug("创建总部主推任务：导入second excel!");
		ReturnMsg<List<String>> returnMsg = new ReturnMsg<List<String>>();

		String value = cacheUtils.get(MainPushConstants.HQ_TASK_PARSE_FIRST_XLS_SUCCESS);
		if (StringUtils.isEmpty(value)) {
			returnMsg.setError(MainPushErrorConstants.TASK_ERR_113, MainPushErrorConstants.MAIN_PUSH_ERR_MAP);
			return returnMsg;
		}

		MultipartRequest mutilRequest = (MultipartRequest) request;
		MultipartFile file = mutilRequest.getFile("secondExcel");
		String month = request.getParameter("month");

		// 参数错误
		if (file == null || month == null || month.length() != 6) {
			returnMsg.setError(MainPushErrorConstants.TASK_ERR_PARAMS, MainPushErrorConstants.MAIN_PUSH_ERR_MAP);
			return returnMsg;
		}

		return mainPushTaskHqHandleService.importSecondExcel(file, month);
	}

	@RequestMapping("/delTask.do")
	@ResponseBody
	public ReturnMsg<HqTask> delTask(Long hqTaskId) {
		LOGGER.info("删除总部主推任务：id：" + hqTaskId);
		if (hqTaskId == null) {
			ReturnMsg<HqTask> returnMsg = new ReturnMsg<HqTask>();
			returnMsg.setRetFlag(ReturnMsg.FAIL);
			returnMsg.setErrorMessage("参数错误");
			return returnMsg;
		}
		return mainPushTaskHqHandleService.delHqTask(hqTaskId);
	}
}
